﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Linq;
using System.IO;
using QuickTasks.ViewModels.Tables;
using System.Collections.Generic;
using LocalSettings;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using QuickTasks.ViewModels;
using QuickTasks.ViewModels.Properties;

namespace QuickTasks.Views.BackGrounds
{
    public class Distance
    {

        bool exists = false;
        double oldlat;
        double oldlong;
        string location;
        string lid;
        int FirstTableId;
        int locationscount;

        public static class GeoCodeCalc
        {
            public const double EarthRadiusInMiles = 3956.0;
            public const double EarthRadiusInKilometers = 6367.0;

            public static double ToRadian(double val) { return val * (Math.PI / 180); }
            public static double DiffRadian(double val1, double val2) { return ToRadian(val2) - ToRadian(val1); }

            public static double CalcDistance(double lat1, double lng1, double lat2, double lng2)
            {
                return CalcDistance(lat1, lng1, lat2, lng2, GeoCodeCalcMeasurement.Miles);
            }

            public static double CalcDistance(double lat1, double lng1, double lat2, double lng2, GeoCodeCalcMeasurement m)
            {
                double radius = GeoCodeCalc.EarthRadiusInMiles;

                if (m == GeoCodeCalcMeasurement.Kilometers) { radius = GeoCodeCalc.EarthRadiusInKilometers; }
                return radius * 2 * Math.Asin(Math.Sqrt((Math.Pow(Math.Sin((DiffRadian(lat1, lat2)) / 2.0), 2.0) + Math.Cos(ToRadian(lat1)) * Math.Cos(ToRadian(lat2)) * Math.Pow(Math.Sin((DiffRadian(lng1, lng2)) / 2.0), 2.0))));
            }
        }

        public enum GeoCodeCalcMeasurement : int
        {
            Miles = 0,
            Kilometers = 1
        }

        public void Cal()
        {
            try
            {
                Dictionary<string, double> dic = new Dictionary<string, double>();
                double mindistance;
                using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                {

                    var lat = from i in context.Add select i;
                    foreach (var latitude in lat)
                    {
                        exists = false;
                        location = latitude.name;
                        if (location == "Any Location")
                        {
                        }
                        else
                        {
                            lid = latitude.id.ToString();
                            oldlat = Convert.ToDouble(latitude.latitude);
                            oldlong = Convert.ToDouble(latitude.longitude);
                            double dis = GeoCodeCalc.CalcDistance(App.Latitude, App.Longitude, oldlat, oldlong, GeoCodeCalcMeasurement.Kilometers);


                            if ((dis / 1000) < 100 || (dis / 1000) < -100)
                            {
                                dic.Add(lid, (dis / 1000));
                            }
                        }
                    }
                    if (dic.Count >= 1)
                    {
                        mindistance = dic.Values.Min();
                        foreach (var d in dic)
                        {
                            if (d.Value == mindistance)
                            {
                                lid = d.Key;
                            }
                        }
                        IQueryable<Location> RowExists = from i in context.Loc where i.id.ToString() == lid select i;
                        if (RowExists.Count() >= 1)
                        {
                            Location RowToDelete = RowExists.FirstOrDefault();
                            context.Loc.DeleteOnSubmit(RowToDelete);
                            context.SubmitChanges();
                        }

                        IEnumerable<Location> locations = (from c in context.Loc select c).ToList();
                        locationscount = locations.Count();
                        while (locationscount > 1)
                        {

                            foreach (var row in locations)
                            {
                                IQueryable<Location> DeleteRow = from i in context.Loc where i.TableId.ToString() == row.TableId.ToString() select i;
                                Location RowToDelete = DeleteRow.FirstOrDefault();
                                if (RowToDelete != null)
                                {
                                    context.Loc.DeleteOnSubmit(RowToDelete);
                                    context.SubmitChanges();
                                }
                                IEnumerable<Location> location = (from c in context.Loc select c).ToList();
                                locationscount = location.Count();
                            }
                        }

                        var plac = from i in context.Add where i.id.ToString() == lid select i;
                        foreach (var locationName in plac)
                        {
                            Location loc1 = new Location()
                            {
                                id = locationName.id,
                                name = locationName.name

                            };
                            context.Loc.InsertOnSubmit(loc1);
                            context.SubmitChanges();
                            break;
                        }
                        if ((!string.IsNullOrEmpty(IsolatedSettings.getSettingsStringValue("GeoLocationStatus1"))) && IsolatedSettings.getSettingsStringValue("GeoLocationStatus1") == "true")
                        {

                            IsolatedSettings.saveSettings("DefaultPlace", lid);
                            properties.props =App.MainPanorama.PanoramaMain.SelectedIndex;
                            App.MainPanorama.LoadMethods();


                        }

                    }
                                     


                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  Cal  method In Distance file", ex);
            }
        }
    }
}